"""认证相关路由"""

from fastapi import APIRouter, HTTPException, Depends
from app.models.auth import LoginRequest, TokenResponse
from app.services.cloud_providers import get_cloud_provider

router = APIRouter()

# 存储用户会话（生产环境应使用 Redis）
user_sessions = {}

@router.post("/login", response_model=TokenResponse)
async def login(credentials: LoginRequest):
    """用户登录"""
    try:
        # 验证云厂商凭证
        provider = get_cloud_provider(
            credentials.provider,
            credentials.access_key,
            credentials.secret_key
        )
        
        # 测试连接
        provider.get_ecs_instances()
        
        # 生成简单 token（生产环境应使用 JWT）
        token = f"{credentials.provider}_{credentials.access_key[:8]}_{hash(credentials.secret_key)}"
        
        # 存储用户会话
        user_sessions[token] = {
            "provider": credentials.provider,
            "access_key": credentials.access_key,
            "secret_key": credentials.secret_key
        }
        
        return TokenResponse(
            token=token,
            provider=credentials.provider,
            expires_in=3600
        )
        
    except Exception as e:
        raise HTTPException(status_code=401, detail=str(e))

@router.post("/logout")
async def logout(token: str):
    """用户登出"""
    if token in user_sessions:
        del user_sessions[token]
    return {"message": "已退出登录"}

def get_current_user(token: str):
    """获取当前用户信息"""
    if token not in user_sessions:
        raise HTTPException(status_code=401, detail="无效的认证令牌")
    return user_sessions[token]
